<%@ page language="java" contentType="text/javascript; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import='java.sql.*' %>
<%@page import="java.util.ArrayList"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONSerializer"%>
<%@page import="net.sf.json.JSONArray"%>
<%@page import="com.google.android.gcm.server.*" %>
<%@page import="javapns.communication.ConnectionToAppleServer"%>
<%@page import="javapns.devices.implementations.basic.BasicDevice"%>
<%@page import="javapns.notification.AppleNotificationServerBasicImpl"%>
<%@page import="javapns.notification.PushNotificationManager"%>
<%@page import="javapns.notification.PushNotificationPayload"%>
<%@page import="javapns.notification.PushedNotification"%>
<%@page import="javapns.notification.ResponsePacket"%>



<%String callback = request.getParameter("callback");%>
<%=callback %> (<%

	String userid = request.getParameter("userid");
	String username = new String(request.getParameter("username").getBytes("8859_1"), "utf-8");
	String hostid = request.getParameter("hostid");
	String hostname = new String(request.getParameter("hostname").getBytes("8859_1"), "utf-8");
	String msg = username + "님이 Ting에 댓글을 등록하였습니다.";
	String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
	String time = new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date());
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	JSONObject jo = new JSONObject();
	
	try{
		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection(
			"jdbc:mysql://localhost/itscreater", "itscreater", "campus123");
		
		String sendcommentmsg = "insert into Message" +
				"(SenderID, Sender, GetterID, Getter, Message, Confirm, Date, Time)" +
				"values (?, ?, ?, ?, ?, ?, ?, ?);";
				
		pstmt = conn.prepareStatement(sendcommentmsg);
		pstmt.setString(1, userid);
		pstmt.setString(2, username);
		pstmt.setString(3, hostid);
		pstmt.setString(4, hostname);
		pstmt.setString(5, msg);
		pstmt.setInt(6, 0);
		pstmt.setString(7, date);
		pstmt.setString(8, time);
		pstmt.executeUpdate();
		
		String regidselect = "select * from gcm where ID = ?;";
		pstmt = conn.prepareStatement(regidselect);
		pstmt.setString(1, hostid);
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next()){
			if (rs.getInt("Device") == 0) {
				String regid = rs.getString("regid");
				String push = rs.getString("Push");
				String vibrate = rs.getString("Vibrate");
				Sender gcmsender = new Sender("AIzaSyC71UD8FmXiaATQ1FUv6fQalDzkMv4qBpg");
				Message message = new Message.Builder()
						//.collapseKey(MESSAGE_ID)
						//.delayWhileIdle(SHOW_ON_IDLE)
						//.timeToLive(LIVE_TIME)
						.addData("push", push)
						.addData("vibrate", vibrate)
						.build();
				Result result = gcmsender.send(message, regid, 5);

				//if(result.getMessageId() != null) {}
					
				//if (result.getErrorCodeName() == "NotRegistered") {
					//String delete = "delete from gcm where ID = ?;";
					//regpstmt = conn.prepareStatement(delete);
					//regpstmt.setString(1, getterID);
					//regpstmt.executeUpdate();
				//}
			} else if (rs.getInt("Device") == 1) {
				String regid = rs.getString("regid");
				
				String host = "gateway.push.apple.com";
				int port = 2195;
				
				String certi = "www/Triends/SUDTriends.p12";
				String passwd = "SUDadventurer2";
				
				PushNotificationPayload payload = new PushNotificationPayload();
				payload.addAlert("쪽지가 왔습니다.");
				//payload.addBadge();
				payload.addSound("default");
				payload.addCustomDictionary("sign", "PushMagic");
				
				BasicDevice device = new BasicDevice(regid);
				device.setDeviceId("iphone");
				
				PushNotificationManager push = new PushNotificationManager();
				
				AppleNotificationServerBasicImpl appleserver = new AppleNotificationServerBasicImpl(certi, passwd, ConnectionToAppleServer.KEYSTORE_TYPE_PKCS12, host, port);
				push.initializeConnection(appleserver);
					
				PushedNotification pushed = push.sendNotification(device, payload);
				
				//ResponsePacket resultPacket = pushed.getResponse();
				
				//if (resultPacket != null) {
					//boolean error = resultPacket.isErrorResponsePacket();
					//boolean error2 = resultPacket.isValidErrorMessage();
					//int error3 = resultPacket.getStatus();
					//String error4 = resultPacket.getMessage();
				//}
				
				push.stopConnection();
			}
			
		}
		jo.put("success", "true");
		out.print(jo);
		
			
	} catch(Exception e) {
		jo.put("success", "true");
		jo.put("error", e);
		out.print(jo);
	}
	
	
	finally{
		try{
			pstmt.close();
		}
		catch (Exception ignored){
		}
		try{
			conn.close();
		}
		catch (Exception ignored){
		}
	}
%>);